package com.aiyi.education.user.controller;


import com.aiyi.education.user.bo.UserRegisterBO;
import com.aiyi.education.entity.KsUser;
import com.aiyi.education.entity.KsUserWithBLOBs;
import com.aiyi.education.user.service.IKsUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.education.annotation.Pass;
import com.education.annotation.ValidationParam;
import com.education.config.ResponseHelper;
import com.education.config.ResponseModel;
import com.education.util.PasswordUtil;
import com.education.util.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author renyong
 * @since 2020-04-22
 */
@Slf4j
@RestController
@Api(tags="用户管理")
@RequestMapping("/user/ks-user")
public class KsUserController {

    @Autowired
    private IKsUserService ksUserService;

    @Autowired
    private RedisUtil redisUtil;


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<KsUserWithBLOBs>> queryPageList(KsUser user, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                               @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<KsUserWithBLOBs>> result = new Result<>();
        QueryWrapper<KsUserWithBLOBs> queryWrapper = new QueryWrapper<>();
        Page<KsUserWithBLOBs> page = new Page<>(pageNo, pageSize);
        String userName=req.getParameter("username");
        if(!StringUtils.isEmpty(userName)){
              queryWrapper.eq("user_name",userName);
        }

        IPage<KsUserWithBLOBs> pageList = ksUserService.page(page,queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        log.info(pageList.toString());
        return result;
    }

    /**
     * 添加用户
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<KsUser>  addUser(@RequestBody JSONObject jsonObject){
        Result<KsUser> result = new Result<KsUser>();
        try{
            KsUser ksUser=JSON.parseObject(jsonObject.toJSONString(), KsUser.class);
            ksUserService.saveSysUser(ksUser);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 删除用户
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestBody KsUserWithBLOBs ksUser) {
        ksUserService.deleteUser(ksUser);
        return Result.ok("删除用户成功");
    }

    /**
     * 批量删除用户
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        ksUserService.deleteBatchUsers(ids);
        return Result.ok("批量删除用户成功");
    }

    /**
     * 修改用户
     * @param ksUserWithBLOBs
     * @return
     */
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public Result<?> edit(@RequestBody KsUserWithBLOBs ksUserWithBLOBs){
        ksUserService.updateById(ksUserWithBLOBs);
        return Result.ok("用户修改成功");
    }

    /**
     * 用户注册接口
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result<JSONObject> userRegister(@RequestBody UserRegisterBO user) {
        Result<JSONObject> result = new Result<JSONObject>();
        String phone=user.getMobile();
        String smscode = user.getCode();
        Object code = redisUtil.get(phone);
        String userName = user.getUserName();
        String realName=user.getRealName();
        String email =user.getEmail();
        KsUser sysUser1 = ksUserService.getUserByParames(userName);
        String password = user.getPassword();
        if (sysUser1 != null) {
            result.setMessage("用户名已注册");
            result.setSuccess(false);
            return result;
        }
        KsUser sysUser2 = ksUserService.getUserByParames(phone);
        if (sysUser2 != null) {
            result.setMessage("该手机号已注册");
            result.setSuccess(false);
            return result;
        }

        if(!StringUtils.isEmpty(email)){
            KsUser sysUser3 = ksUserService.getUserByParames(email);
            if (sysUser3 != null) {
                result.setMessage("邮箱已被注册");
                result.setSuccess(false);
                return result;
            }
        }

        if (!smscode.equals(code)) {
            result.setMessage("手机验证码错误");
            result.setSuccess(false);
            return result;
        }
        try {
            user.setRegDate(new Date());//注册日期
            user.setJoinDate(new Date());// 设置创建时间
            String salt = PasswordUtil.randomGen(8);
            String passwordEncode = PasswordUtil.encrypt(userName, password, salt);
            user.setSalt(salt);
            user.setUserName(userName);
            user.setRealName(realName);
            user.setPassword(passwordEncode);
            user.setEmail(email);
            user.setMobile(phone);
            user.setLocked(0);
            result.success("注册成功");
        } catch (Exception e) {
            result.error500("注册失败");
        }
        return result;
    }


    @ApiOperation(value="手机验证码注册", notes="body体参数,不需要Authorization",produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "requestJson", value = "{\"username\":\"\",\"mobile\":\"13888888888\",</br>" +
                    "\"captcha\":\"5780\",\"password\":\"123456\",</br>\"rePassword\":\"123456\",\"job\":\"java开发\"," +
                    "</br>\"unit(可不传)\":\"xxx公司\"}"
                    , required = true, dataType = "String",paramType="body")
    })
    @PostMapping("/user_register")
    //@Log(action="register",modelName= "home_owner_login",description="注册接口")
    @Pass
    public ResponseModel<KsUserWithBLOBs> register(//@ValidationParam("username,password,rePassword,mobile,captcha,job")
                                             @RequestBody JSONObject requestJson)throws Exception {
        return ResponseHelper.buildResponseModel( ksUserService.checkAndRegisterUser(requestJson));
    }

    @ApiOperation(value="用户账号登录", notes="body体参数,不需要Authorization",produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "requestJson", value = "{\"mobile\":\"13888888888\",\"password\":\"123456\"}"
                    , required = true, dataType = "String",paramType="body")
    })
    @PostMapping("/user_login")
    @Pass
    public ResponseModel<Map<String, Object>> login(
            @ValidationParam("userAccount,password")@RequestBody JSONObject requestJson) throws Exception{
        return ResponseHelper.buildResponseModel(ksUserService.checkLoginAccountAndPasswd(requestJson));
    }
}
